# DRF的GenericAPIView、Response
# t拓展类必须配合GenericAPIView 一块使用
from rest_framework.mixins import ListModelMixin, CreateModelMixin, UpdateModelMixin, DestroyModelMixin, \
    RetrieveModelMixin
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from books.serialziers import BookModelSerializer
from books.models import BookInfo


class BooksView(GenericAPIView, ListModelMixin, CreateModelMixin):
    # 指定查询集属性
    queryset = BookInfo.objects.all()
    # 指定序列化器属性
    serializer_class = BookModelSerializer

    def post(self, request):
        """
           保存图书
       :param request:
       :return:
        """
        return self.create(request)

    def get(self, request):
        """
                获取所有图书
               :param request:
               :return:
        """
        return self.list(request)


class BookView(GenericAPIView):
    # 指定查询集属性
    queryset = BookInfo.objects.all()
    # 指定序列化器属性
    serializer_class = BookModelSerializer

    def delete(self, request, pk):
        """
             删除一本图书
         :param request:
         :param pk: 图书id
         :return:
         """
        try:
            # get_object 获取queryse属性中的一个数据对象，会根据传递的id值自动判断
            book = self.get_object()
        except:
            return Response({'code': '400'}, status=400)
        # 逻辑删除
        book.is_delete = True
        book.save()
        # 物理删除
        # book.delete()
        return Response({})

    def put(self, request, pk):
        """
            更新一本图书
        :param request:
        :param pk: 图书id
        :return:
        """
        # 查询更新的图书 get_object 获取queryse属性中的一个数据对象，会根据传递的id值自动判断
        try:
            book = self.get_object()
        except:
            return Response({'code': '400', 'message': '数据不存在'}, status=400)
        # 获取更新的字段
        data = request.data
        # 验证数据
        ser = self.get_serializer(book, data=data)
        try:
            ser.is_valid(raise_exception=True)
        except:
            return Response({'error': '字段验证失败'}, status=400)
        # 更新数据
        ser.save()
        # 返回结果
        return Response(ser.data)

    def get(self, request, pk):
        """
            获取一本图书
        :param request:
        :param pk:  图书id
        :return:
        """
        try:
            book = self.get_object()  # get_object 获取queryse属性中的一个数据对象，会根据传递的id值自动判断
        except Exception as e:
            print(e)
            return Response({'code': '400', 'message': '数据不存在'}, status=400)
        ser = self.get_serializer(book)
        return Response(ser.data)